package com.example.controller;

import com.example.entity.Books;
import com.example.service.JSMindService;
import com.example.service.StudentService;
import com.example.service.TeacherService;
import com.example.service.UserService;
import com.example.utils.Msg;
import com.example.utils.Time;
import com.google.code.kaptcha.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Set;

/**
 * @author： wzz
 * @date： 2021-07-13 13:36
 */

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private StudentService studentService;
    @Resource
    UserService userService;
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private JSMindService jsMindService;

    @GetMapping("/403")
    public String Forbidden() {
        return "403";
    }

    /**
     * 首页重定向
     *
     * @return
     */
    @RequestMapping("/")
    public String Init() {
        return "redirect:/index";
    }

    /**
     * 首页
     *
     * @return
     */
    @GetMapping("/index")
    public String Index(Model model, Authentication authentication) {
        if (authentication.getAuthorities().toString().equals("[ROLE_student]")) {
            if (userService.IsFirstLogin(authentication.getName(), true) && authentication.getName()!=null) {
                return "redirect:/front/password/1/1";
            }
            userService.UpdateLoginTime(authentication.getName(), Time.getTime(),true);
            List<Books> bookList = studentService.GetStuBook(authentication.getName());
            model.addAttribute("bookList", bookList);
            return "front/index";
        } else return "redirect:back/index";


    }

    /**
     * 登录界面
     *
     * @return
     */
    @GetMapping("/login")
    public String Login() {
        return "login";
    }

    /**
     * 检查验证码
     *
     * @param verifycode
     * @param session
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("/checkCode")
    @ResponseBody
    public Msg CheckCode(@RequestParam("code") String code,
                         HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {

//        String sessionCode = (String) session.getAttribute(VerifyCodeController.SESSION_KEY);
//        System.out.println(sessionCode);
//        if (null == sessionCode) {
//            return Msg.fail().add("mc_msg", "验证码超时");
//        }
//        if (!sessionCode.equalsIgnoreCase(verifycode)) {
//            return Msg.fail().add("mc_msg", "验证码错误");
//        }
//        session.removeAttribute(VerifyCodeController.SESSION_KEY);
        String sessionCode = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println(" session中获取的验证码:  " + sessionCode);
        if (code.equalsIgnoreCase(sessionCode)){
            return Msg.success();
        }else {
            return Msg.fail().add("mc_msg", "验证码错误");
        }
    }

    /**
     * 修改密码跳转
     *
     * @return
     */
    @RequestMapping("/front/password/{isFirst}/{isStu}")
    public String password(Model model, @PathVariable int isFirst,
                           @PathVariable int isStu) {
        if(isFirst==1) model.addAttribute("isFirst",true);
        else model.addAttribute("isFirst",false);
        if(isStu==1) model.addAttribute("isStu",true);
        else model.addAttribute("isStu",false);
        return "front/password";
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @param authentication
     * @return
     */
    @PostMapping(value = "/user/updatePassword")
    @ResponseBody
    public Msg updatePassword(@RequestParam("oldPassword") String oldPassword,
                              @RequestParam("newPassword") String newPassword,
                              Authentication authentication) {

        newPassword = new BCryptPasswordEncoder().encode(newPassword);
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        String num = authentication.getName();
        System.out.println(authentication.getPrincipal());
        int result = 0;
        //登录用户和密码检测
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (roles.contains("ROLE_student")) {
            if (encoder.matches(oldPassword, userService.getUserPassword(num, true))) {
                if(userService.UpdateUserPassword(num, newPassword, true)!=0){
                    userService.UpdateLoginTime(authentication.getName(), Time.getTime(),true);
                    log.info("更新密码成功");
                    return Msg.success();
                }else {
                    log.info("更新密码失败");
                    return Msg.fail();
                }

            }
        } else {
            if (encoder.matches(oldPassword, userService.getUserPassword(num, false))) {
                 if(userService.UpdateUserPassword(num, newPassword, false)!=0){
                     userService.UpdateLoginTime(authentication.getName(), Time.getTime(),false);
                     log.info("更新密码成功");
                     return Msg.success();
                 }else{
                     log.info("更新密码失败");
                     return Msg.fail();
                 }
            }
        }
        return Msg.fail();
    }
    @GetMapping("/user/my/{page}")
    public String myInformation(Model model,
                                Authentication authentication,
                                @PathVariable String page) {
        Boolean isStu= false;
        String num = authentication.getName();
        if(page.equals("back")){
            model.addAttribute("user", teacherService.GetTeacherByNum(num));
        }
        else if(page.equals("front")){
            model.addAttribute("user",studentService.queryOne(num));
            isStu = true;

        }
        model.addAttribute("isStu",isStu);
        return "MyInformation";
    }
}
